package es

import (
	"context"
	"encoding/json"
	"github.com/olivere/elastic/v7"
	"project/weeksrv/global"
	"project/weeksrv/weeksrv"
)

func GetGoodsEsSearchByName(query elastic.Query) ([]*weeksrv.Goods, error) {
	res, err := global.EsClient.Search().Index("goods").Query(query).Do(context.Background())
	if err != nil {
		return nil, err
	}
	return EsToProtoGoods(res), nil
}
func GetGoodsSort(SortId int) ([]*weeksrv.Goods, error) {
	var res *elastic.SearchResult
	var err error
	switch SortId {
	case 1:
		res, err = global.EsClient.Search().Index(global.ES_INDEX).Sort("goods_price", false).Do(context.Background())
	case 2:
		res, err = global.EsClient.Search().Index(global.ES_INDEX).Sort("goods_comment", false).Do(context.Background())
	default:
		res, err = global.EsClient.Search().Index(global.ES_INDEX).Do(context.Background())
	}
	if err != nil {
		return nil, err
	}
	return EsToProtoGoods(res), nil
}
func EsToProtoGoods(res *elastic.SearchResult) []*weeksrv.Goods {
	var goodsMaps []map[string]interface{}
	for _, hit := range res.Hits.Hits {
		var goodsMap map[string]interface{}
		json.Unmarshal(hit.Source, &goodsMap)
		for i, v := range hit.Highlight {
			goodsMap[i] = v[0]
		}
		goodsMaps = append(goodsMaps, goodsMap)
	}
	var GoodsList []*weeksrv.Goods
	for _, v := range goodsMaps {
		GoodsList = append(GoodsList, &weeksrv.Goods{
			GoodsName:  v["goods_name"].(string),
			GoodsPrice: float32(v["goods_price"].(float64)),
			GoodsStock: int32(v["goods_stock"].(float64)),
			GoodsDesc:  v["goods_desc"].(string),
			GoodsSales: int32(v["goods_comment"].(float64)),
		})
	}
	return GoodsList
}
